package com.ywu.application.standard.fileSys.utils;

import com.ywu.boot.exception.YwuRuntimeException;
import com.ywu.common.constant.CommonConstant;
import com.ywu.common.gson.GsonUtils;
import com.ywu.common.result.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Objects;

/**
 * @ClassName ResponseUtils
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/8/10 16:31
 * @Version 1.0
 **/
@Slf4j
@Component
public class ResponseUtils {

    /**
    * @Author GroundDemo
    * @Description response写入common响应体
    * @Date 16:33 2024/8/10
    * @Param [response, result]
    * @return void
    **/
    public static void writeResponse(HttpServletResponse response, CommonResult<Object> result) {
        // 设置响应内容类型
        response.setContentType("application/json");
        // 设置状态码
        if (Objects.equals(result.getCode(), CommonConstant.SUCCESS_CODE)) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
        // 获取PrintWriter来写入响应体
        PrintWriter out = null;
        try {
            out = response.getWriter();
            // 写入响应体
            String serialize = GsonUtils.serialize(result);
            out.write(serialize);
        } catch (IOException e) {
            log.error("writeResponse IOException error {}", e.getMessage());
            throw new YwuRuntimeException("writeResponse IOException error");
        }
    }

    /**
    * @Author GroundDemo
    * @Description 写入响应文件
    * @Date 16:41 2024/8/10
    * @Param [response, file, type]
    * @return void
    **/
    public static void writeResponseFile(HttpServletResponse response, File file, String type) {
        // 判断是否存在
        if (!file.exists()) {
            CommonResult<Object> result = CommonResult.error().setErrorCode("file.path.is.not.exists")
                    .setMessage("文件路劲不存在");
            writeResponse(response, result);
            return;
        }
        String fileName = file.getName();
        // 设置response的Header
        response.setCharacterEncoding("UTF-8");
        // 指定下载文件名(attachment-以下载方式保存到本地，inline-在线预览)
        String resFileName = null;
        try {
            resFileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (!StringUtils.equals(type, "inline")) {
            // 不是在线播放时才会添加Content-Disposition
            response.setHeader("Content-Disposition", "attachment; filename=" + resFileName + "");
        }
        // 告知浏览器文件的大小
        response.addHeader("Content-Length", "" + file.length());
        // 内容类型为通用类型，表示二进制数据流
        if (fileName.endsWith(".m3u8") && StringUtils.equals(type, "inline")) {
            response.setContentType("application/vnd.apple.mpegurl");
        } else {
            response.setContentType("application/octet-stream");
        }
        try(InputStream is = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())){
            byte[] buff = new byte[2048];
            int len;
            while ((len = bis.read(buff)) != -1){
                bos.write(buff, 0, len);
            }
            bos.flush();
        } catch (IOException e){
            log.error("writeResponseFile IOException error {}", e.getMessage());
            throw new YwuRuntimeException("writeResponseFile IOException error");
        }
    }
}
